<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加科研成果</el-button>
    <el-table :data="outputs" style="margin-top: 10px" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="成果标题" />
      <el-table-column prop="outputType" label="成果类型" width="120" />
      <el-table-column prop="rawScore" label="评分" width="100" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="科研成果" @close="resetForm">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="成果标题" prop="title">
          <el-input v-model="formData.title" />
        </el-form-item>

        <el-form-item label="成果类型" prop="outputType">
          <el-select v-model="formData.outputType" placeholder="请选择成果类型" clearable>
            <el-option label="论文" value="论文" />
            <el-option label="专利" value="专利" />
            <el-option label="软件著作权" value="软件著作权" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="评分" prop="rawScore">
          <el-input-number v-model="formData.rawScore" :min="0" />
        </el-form-item>

        <el-form-item label="发表/授权日期" required>
          <el-date-picker
              v-model="formData.publicationDate"
              type="date"
              placeholder="请选择日期"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'ResearchOutputsModule',
  props: {
    studentId: { type: Number, required: true }
  },
  data() {
    return {
      outputs: [],
      dialogVisible: false,
      formData: {
        id: null,
        studentId: null,
        title: '',
        outputType: '',
        rawScore: null
      },
      rules: {
        title: [{ required: true, message: '请输入成果标题', trigger: 'blur' }],
        outputType: [{ required: true, message: '请选择成果类型', trigger: 'change' }],
        rawScore: [{ required: true, message: '请输入评分', trigger: 'blur' }]
      }
    }
  },
  watch: {
    studentId: {
      handler(newVal) {
        if (typeof newVal === 'number' && !isNaN(newVal)) {
          this.loadData()
        } else {
          this.outputs = []
        }
      },
      immediate: true
    }
  },
  methods: {
    async loadData() {
      try {
        const res = await axios.get(`/api/researchoutputs/student/${this.studentId}`)
        this.outputs = res.data || []
      } catch (e) {
        this.$message.error('加载科研成果失败')
        console.error('加载科研成果失败:', e)
      }
    },
    openAddDialog() {
      this.formData = {
        id: null,
        studentId: this.studentId,
        title: '',
        outputType: '',
        rawScore: null
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.formData = { ...row, studentId: this.studentId }
      this.dialogVisible = true
    },
    async submit() {
      try {
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        this.formData.studentId = this.studentId
        let res
        if (this.formData.id) {
          res = await axios.put('/api/researchoutputs', this.formData)
        } else {
          res = await axios.post('/api/researchoutputs', this.formData)
        }

        if (res.data.code === 200 || res.data > 0) {
          this.$message.success(this.formData.id ? '更新成功' : '添加成功')
          this.dialogVisible = false
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error(res.data.message || (this.formData.id ? '更新失败' : '添加失败'))
        }
      } catch (e) {
        this.$message.error('提交失败')
        console.error('提交科研成果失败:', e)
      }
    },
    async handleDelete(id) {
      try {
        const res = await axios.delete(`/api/researchoutputs/${id}`)
        if (res.data.code === 200 || res.data > 0) {
          this.$message.success('删除成功')
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error('删除失败')
        }
      } catch (e) {
        this.$message.error('删除失败')
        console.error('删除科研成果失败:', e)
      }
    },
    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = {
        id: null,
        studentId: this.studentId,
        title: '',
        outputType: '',
        rawScore: null
      }
    }
  }
}
</script>
